package com.lanxiao.cloud.modules.log.application;

import com.lanxiao.cloud.common.core.dto.PageQuery;
import com.lanxiao.cloud.common.core.dto.ResultModel;
import com.lanxiao.cloud.common.core.enums.OperationType;
import com.lanxiao.cloud.common.core.utils.StringUtils;
import com.lanxiao.cloud.modules.log.application.assembler.LogAssembler;
import com.lanxiao.cloud.modules.log.application.dto.LogDto;
import com.lanxiao.cloud.modules.log.application.dto.LogQuery;
import com.lanxiao.cloud.modules.log.domain.Log;
import java.util.List;
import java.util.Objects;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-10-15
 */
@Component
public class LogQueryManager {

  private final LogAssembler logAssembler;
  private final MongoTemplate mongoTemplate;

  public LogQueryManager(
      LogAssembler logAssembler, MongoTemplate mongoTemplate) {
    this.logAssembler = logAssembler;
    this.mongoTemplate = mongoTemplate;
  }

  public ResultModel<LogDto> page(boolean isLogin, LogQuery logQuery, PageQuery pageable) {

    Criteria criteria = new Criteria();
    if(isLogin) {
      criteria.and("type").is(OperationType.LOGIN);
    }else if(Objects.nonNull(logQuery.getType())){
      criteria.and("type").is(logQuery.getType());
    }else {
      criteria.and("type").ne(OperationType.LOGIN);
    }
    if(StringUtils.isNotBlank(logQuery.getService())) {
      criteria.and("topic.name").is(logQuery.getService());
    }
    if(StringUtils.isNotBlank(logQuery.getCreateBy())) {
      criteria.and("createBy").is(logQuery.getCreateBy());
    }
    if(StringUtils.isNotBlank(logQuery.getIp())) {
      criteria.and("ip").is(logQuery.getIp());
    }
    if(Objects.nonNull(logQuery.getStartTime())) {
      criteria.and("createTime").gt(logQuery.getStartTime());
    }
    if(Objects.nonNull(logQuery.getEndTime())) {
      criteria.and("createTime").lt(logQuery.getEndTime());
    }
    //必要条件
    Query query = new Query(criteria);
    int count = (int) mongoTemplate.count(query, Log.class);
    //分页参数
    query.with(PageRequest.of(
        pageable.getPage()>0?pageable.getPage()-1:pageable.getPage(),
        pageable.getSize(),
        Sort.by(Direction.DESC, "createTime")));
    // 查询总数
    List<Log> list = mongoTemplate.find(query, Log.class);
    return logAssembler.toLogDto(list, count);
  }

}
